<?php

namespace common\widgets;

/**
 * 文件上传
 *
 * @package common\widgets
 */
class FileInput extends \kartik\widgets\FileInput
{

    /**
     * @var bool 是否自动上传
     */
    public $autoUpload = false;

    /**
     * @var string 自动上传地址
     */
    public $autoUploadUrl = '/upload/index/index';

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        // 如果是自动上传的话,对于上传按钮那里要进行一些额外的配置
        if ($this->autoUpload)
        {
            //$this->options['name'] = $this->id . '_file_upload';
        }
        parent::init();
    }

    /**
     * {@inheritdoc}
     */
    public function registerAssets()
    {
        if ($this->autoUpload && ! isset($this->pluginOptions['uploadUrl']))
        {
            $this->pluginOptions['uploadUrl'] = $this->autoUploadUrl;
        }
        parent::registerAssets();
        if ($this->autoUpload)
        {
            $id = "jQuery('#" . $this->options['id'] . "')";
            $hiddenInput = "jQuery('input:hidden[name=\"{$this->name}\"]')";
            //var_dump($hiddenInput);die();
            $this->view->registerJs("
{$id}.on('fileselect', function(event, files) {
    {$id}.fileinput('upload');
}).on('fileuploaded', function (outData, previewId, i) {
    if (previewId.response.url !== undefined) {
        {$hiddenInput}.val(previewId.response.url);
    }
});\n");
        }
    }
}
